<template>
  <div class="app-container">
    <div class="card-box">
      <el-space>
        <el-button type="primary" @click="handleToAdd">添加快递单</el-button>
      </el-space>
    </div>
    <div class="card-box">
      <el-table v-loading="expressStore.loading.list" :data="expressStore.list">
        <el-table-column label="快递公司" prop="company.name" />
        <el-table-column label="快递单号" prop="code" />
        <el-table-column label="源订单号" prop="origin" />
        <el-table-column label="创建时间" prop="created_at" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" link @click="handleToEdit(scope.row)">编辑</el-button>
            <el-popconfirm title="确定删除吗？" placement="top" @confirm="handleDelete(scope.row)">
              <template #reference>
                <el-button type="danger" link>删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="expressStore.list.length > 0"
        v-model:current-page="params.page"
        v-model:page-size="params.size"
        background
        style="margin-top: 10px"
        :total="expressStore.totalCount"
      />
    </div>
    <Form v-model="visible" :type="formType" :form-data="currentForm" @confirm="handleConfirm" />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { useExpressStoreHook } from "@/store/modules/logistics/express";
import Form from "./components/form.vue";
import type { ExpressType, ExpressForm } from "@/api/logistics/express";

const expressStore = useExpressStoreHook();

const params = reactive({
  page: 1,
  size: 10,
});

const visible = ref(false);
const formType = ref<"add" | "edit">("add");
const currentForm = ref<ExpressForm>({
  code: "",
  company: "",
  origin: "",
});

function handleToAdd() {
  formType.value = "add";
  currentForm.value = {
    code: "",
    company: "",
    origin: "",
  };
  visible.value = true;
}

function handleToEdit(row: ExpressType) {
  formType.value = "edit";
  currentForm.value = {
    id: row.id,
    code: row.code,
    company: row.company.id,
    origin: row.origin,
  };
  visible.value = true;
}

async function handleDelete(row: ExpressType) {
  await expressStore.fetchDeleteExpress(row.id);
  await expressStore.fetchExpressList(params);
}

function handleConfirm() {
  expressStore.fetchExpressList(params);
}

onMounted(() => {
  expressStore.fetchExpressList(params);
});
</script>

<style scoped lang="scss"></style>
